Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass -Force
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$ErrorActionPreference = "Stop"

$progressStyle = @{ ForegroundColor = 'Cyan'; BackgroundColor = 'Black' }
$successStyle = @{ ForegroundColor = 'Green'; BackgroundColor = 'Black' }
$errorStyle = @{ ForegroundColor = 'Red'; BackgroundColor = 'Black' }



# 检查签名配置
$keyPropertiesPath = "android/key.properties"
$keyStorePath = "key.jks"

if (-not (Test-Path $keyPropertiesPath)) {
	
    Write-Host "错误: 未找到签名配置文件 android/key.properties" -ForegroundColor Red
    exit 1
}

if (-not (Test-Path $keyStorePath)) {
    Write-Host "错误: 未找到签名文件 key.jks" -ForegroundColor Red
    exit 1
}

# 清理构建
Write-Host "清理旧构建..." -ForegroundColor Cyan
flutter clean

# 获取 pub 依赖
Write-Host "获取依赖..." -ForegroundColor Cyan
flutter pub get

# 构建 Android 发布版本
Write-Host "开始构建带签名的 Android 发布版本..." -ForegroundColor Green

if ($BuildAppBundle) {
    # 构建 App Bundle
    Write-Host "构建带签名的 App Bundle..." -ForegroundColor Yellow
    flutter build appbundle --release
    
    $bundlePath = "$PSScriptRoot\build\app\outputs\bundle\release\app-release.aab"
    if (Test-Path $bundlePath) {
        Write-Host "App Bundle 构建成功: $bundlePath" -ForegroundColor Green
        
        # 验证签名
        Write-Host "验证签名信息..." -ForegroundColor Cyan
        jarsigner -verify -verbose -certs $bundlePath
    } else {
        Write-Host "App Bundle 构建失败" -ForegroundColor Red
    }
} else {
    # 构建 APK
    Write-Host "构建带签名的 APK..." -ForegroundColor Yellow
    flutter build apk --release
    
    $apkPath = "$PSScriptRoot\build\app\outputs\flutter-apk\app-release.apk"
    if (Test-Path $apkPath) {
        Write-Host "APK 构建成功: $apkPath" -ForegroundColor Green
        
        # 验证签名
        Write-Host "验证签名信息..." -ForegroundColor Cyan
        jarsigner -verify -verbose -certs $apkPath
    } else {
        Write-Host "APK 构建失败" -ForegroundColor Red
    }
}

Write-Host "OK" -ForegroundColor Cyan
Read-Host "`n按 Enter 键退出..."